/**
 * Created by Administrator on 2017/3/10.
 */

var crypto = require('crypto');
var CONFIG = require('../config');
var request = require('request');

(function () {
    var randomString = this.randomString = function (len) {
        len = len || 32;
        var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
        var maxPos = $chars.length;
        var pwd = '';
        for (var i = 0; i < len; i++) {
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    };

    //格林威治时间转换
    var handle = this.handle = function (data) {
        if (data.created_date != undefined) {
            data.created_date = format_time(data.created_date);
        }

        if (data.updated_date != undefined) {
            data.updated_date = format_time(data.updated_date);
        }
        return data;
    }

    function format_time(str) {
        if (str.indexOf('.000Z') >= 0) {
            str = str.replace(/T/, ' ');
            str = str.replace(/.000Z/, ' ');
            var a1;
            var a2;
            a1 = str.split(' ');
            a2 = a1[1].split(':');
            a2[0] = parseInt(a2[0]) + 8;
            if (a2[0] >= 24) {
                a1[0] = a1[0].split('-');
                a1[0][2] = parseInt(a1[0][2]) + 1;
                a1[0] = a1[0].join('-');
                a2[0] = a2[0] - 24;
                if (a2[0] < 10) {
                    a2[0] = '0' + a2[0];
                }
            }
            a2 = a2.join(':');
            var update_time = a1[0] + ' ' + a2;
            return update_time;
        } else {
            return str;
        }
    }

    var paramAll = this.paramAll = function (req) {
        var parameter = {};
        if (req.params) {
            for (var p in req.params) {
                parameter[p] = req.params[p];
            }
        }
        if (req.body) {
            for (var p in req.body) {
                parameter[p] = req.body[p];
            }
        }
        if (req.query) {
            for (var p in req.query) {
                parameter[p] = req.query[p];
            }
        }
        return parameter;
    };

    var simpleDateFormat = this.simpleDateFormat = function (time) {
        var d = new Date(time);
        var month = d.getMonth() + 1;
        if (month < 10) {
            month = '0' + month;
        }
        var date = d.getDate();
        if (date < 10) {
            date = '0' + date;
        }
        var hour = d.getHours();
        if (hour < 10) {
            hour = '0' + hour;
        }
        var minute = d.getMinutes();
        if (minute < 10) {
            minute = '0' + minute;
        }
        var second = d.getSeconds();
        if (second < 10) {
            second = '0' + second;
        }
        return d.getFullYear() + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second;
    }

    var formatTime = this.formatTime = function (str) {
        if (str.indexOf('.000Z') >= 0) {
            str = str.replace(/T/, ' ');
            str = str.replace(/.000Z/, ' ');
            var a1;
            var a2;
            a1 = str.split(' ');
            a2 = a1[1].split(':');
            a2[0] = parseInt(a2[0]) + 8;
            if (a2[0] >= 24) {
                a1[0] = a1[0].split('-');
                a1[0][2] = parseInt(a1[0][2]) + 1;
                a1[0] = a1[0].join('-');
                a2[0] = a2[0] - 24;
                if (a2[0] < 10) {
                    a2[0] = '0' + a2[0];
                }
            }
            a2 = a2.join(':');
            var update_time = a1[0] + ' ' + a2;
            return update_time;
        } else {
            return str;
        }
    };

    function convertToUnicode(data) {
        var reg = /\\u[0-9a-f]{4}/igm;
        return data.replace(reg, function () {
            return String.fromCharCode(parseInt(arguments[0].substr(2, 4), 16).toString())
        });
    };

    //计算与1970年1月相差月份
    var getAfter1970Months = this.getAfter1970Months = function (nowYear,nowMonth){
        //规则：（当前年份-起始年份)*12+当前月份-起始月份
        var count = (nowYear - 1970)*12 + (nowMonth - 1);
        return count;
    }

    //计算sign
    var getAppSign = this.getAppSign = function (APP_key,APP_secret,t){
        var md5=crypto.createHash('md5');
        md5.update(""+APP_key+APP_secret+t);
        var sign = md5.digest('hex');
        return sign;
    }


    var getParWithSign = this.getParWithSign = function (APP_key,APP_secret) {
        var time = new Date().getTime();
        var par = {
            app_key: APP_key,
            app_time: time,
            app_sign: getAppSign(APP_key,APP_secret,time)
        }
        return par;
    }

    var dropFloatTail = this.dropFloatTail = function (f) {
        f = parseFloat(f).toFixed(2);
        if(f.substr(f.length - 2) == '00') return f.substr(0, f.length - 3);
        if(f.substr(f.length - 1) == '0' ) return f.substr(0, f.length - 1);
        return f;
    }

    var addSignToPar = this.addSignToPar = function (par,APP_key,APP_secret) {
        var time = new Date().getTime();
        par.app_key = APP_key;
        par.app_time = time;
        par.app_sign = getAppSign(APP_key,APP_secret,time);
    }

    var checkSrvConnection = this.checkSrvConnection = function (par) {
        var sign = getAppSign(par.app_key,CONFIG.APP_secret, par.app_time);
        return sign == par.app_sign ? true : false;
    }

    var baseRequest = this.baseRequest = function(host, path, param, callback) {
        var url = host + path;
        var form = '';
        for(var key in param){
            form += key + '='  + param[key] + '&';
        }
        var options = {
            url: url,
            method: 'POST',
            form: form
        };
        request(options, function (error, response, body) {
            if (error || !response || response.statusCode != 200 || !body) {
                callback('服务器异常，请稍后重试');
                console.log(error);
                return;
            } else {
                try {
                    body = JSON.parse(body);
                    if(body.status == 200){
                        callback(null,body.payload);
                        return;
                    }
                    callback(body.err);
                } catch (e) {
                    callback('服务器异常，请稍后重试');
                }
            }
        });
    }
})();